{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
    "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/geemap/tree/master/tutorials/Image/11_texture.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/geemap/blob/master/tutorials/Image/11_texture.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
    "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/geemap/blob/master/tutorials/Image/11_texture.ipynb\"><img width=26px src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Texture\n",
    "Earth Engine has several special methods for estimating spatial texture. When the image is discrete valued (not floating point), you can use `image.entropy()` to compute the [entropy](http://en.wikipedia.org/wiki/Entropy_(information_theory)) in a neighborhood:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install Earth Engine API and geemap\n",
    "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
    "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n",
    "\n",
    "**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installs geemap package\n",
    "import subprocess\n",
    "\n",
    "try:\n",
    "    import geemap\n",
    "except ImportError:\n",
    "    print('geemap package not installed. Installing ...')\n",
    "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n",
    "\n",
    "# Checks whether this notebook is running on Google Colab\n",
    "try:\n",
    "    import google.colab\n",
    "    import geemap.eefolium as emap\n",
    "except:\n",
    "    import geemap as emap\n",
    "\n",
    "# Authenticates and initializes Earth Engine\n",
    "import ee\n",
    "\n",
    "try:\n",
    "    ee.Initialize()\n",
    "except Exception as e:\n",
    "    ee.Authenticate()\n",
    "    ee.Initialize()  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create an interactive map \n",
    "The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = emap.Map(center=[40,-100], zoom=4)\n",
    "Map.add_basemap('ROADMAP') # Add Google Map\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add Earth Engine Python script "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "# Load a high-resolution NAIP image.\n",
    "image = ee.Image('USDA/NAIP/DOQQ/m_3712213_sw_10_1_20140613')\n",
    "\n",
    "# Zoom to San Francisco, display.\n",
    "Map.setCenter(-122.466123, 37.769833, 17)\n",
    "Map.addLayer(image, {'max': 255}, 'image')\n",
    "\n",
    "# Get the NIR band.\n",
    "nir = image.select('N')\n",
    "\n",
    "# Define a neighborhood with a kernel.\n",
    "square = ee.Kernel.square(**{'radius': 4})\n",
    "\n",
    "# Compute entropy and display.\n",
    "entropy = nir.entropy(square)\n",
    "Map.addLayer(entropy,\n",
    "             {'min': 1, 'max': 5, 'palette': ['0000CC', 'CC0000']},\n",
    "             'entropy')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the NIR band is scaled to 8-bits prior to calling `entropy()` since the entropy computation takes discrete valued inputs. The non-zero elements in the kernel specify the neighborhood.\n",
    "\n",
    "Another way to measure texture is with a gray-level co-occurrence matrix (GLCM). Using the image and kernel from the previous example, compute the GLCM-based contrast as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the gray-level co-occurrence matrix (GLCM), get contrast.\n",
    "glcm = nir.glcmTexture(**{'size': 4})\n",
    "contrast = glcm.select('N_contrast')\n",
    "Map.addLayer(contrast,\n",
    "             {'min': 0, 'max': 1500, 'palette': ['0000CC', 'CC0000']},\n",
    "             'contrast')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many measures of texture are output by `image.glcm()`. For a complete reference on the outputs, see [Haralick et al. (1973)](http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=4309314&tag=1) and [Conners et al. (1984)](http://www.sciencedirect.com/science/article/pii/0734189X8490197X).\n",
    "\n",
    "Local measures of spatial association such as Geary’s C [(Anselin 1995)](http://onlinelibrary.wiley.com/doi/10.1111/j.1538-4632.1995.tb00338.x/abstract) can be computed in Earth Engine using `image.neighborhoodToBands()`. Using the image from the previous example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a list of weights for a 9x9 kernel.\n",
    "list = [1, 1, 1, 1, 1, 1, 1, 1, 1]\n",
    "# The center of the kernel is zero.\n",
    "centerList = [1, 1, 1, 1, 0, 1, 1, 1, 1]\n",
    "# Assemble a list of lists: the 9x9 kernel weights as a 2-D matrix.\n",
    "lists = [list, list, list, list, centerList, list, list, list, list]\n",
    "# Create the kernel from the weights.\n",
    "# Non-zero weights represent the spatial neighborhood.\n",
    "kernel = ee.Kernel.fixed(9, 9, lists, -4, -4, False)\n",
    "\n",
    "# Convert the neighborhood into multiple bands.\n",
    "neighs = nir.neighborhoodToBands(kernel)\n",
    "\n",
    "# Compute local Geary's C, a measure of spatial association.\n",
    "gearys = nir.subtract(neighs).pow(2).reduce(ee.Reducer.sum()) \\\n",
    "             .divide(math.pow(9, 2))\n",
    "Map.addLayer(gearys,\n",
    "             {'min': 20, 'max': 2500, 'palette': ['0000CC', 'CC0000']},\n",
    "             \"Geary's C\")\n",
    "\n",
    "Map.addLayerControl()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For an example of using neighborhood standard deviation to compute image texture, see the [Statistics of Image Neighborhoods page](https://developers.google.com/earth-engine/reducers_reduce_neighborhood)."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
